package com.jy.modules.cims.interact;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jy.modules.cims.common.CimsIrtUrlConstant;
import com.jy.modules.cims.common.JResult;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.HttpUtils;
import com.jy.modules.cims.common.sysUtils.PropertyUtil;
import com.jy.modules.cims.common.sysUtils.SimpleBeanUtils;
import com.jy.modules.cims.data.dto.CustomerDto;
import com.jy.modules.cims.data.interact.core.bds.request.RequestCustomerCreateOrupdateDTO;
import com.jy.modules.cims.data.interact.core.bds.request.RequestCustomerValidateDTO;
import com.jy.modules.cims.data.interact.core.bds.request.RequestRepaymentPlanDTO;
import com.jy.modules.cims.data.interact.core.bds.response.ResponseCustomerValidateDTO;
import com.jy.modules.cims.data.interact.core.bds.response.ResponseRepaymentPlanDTO;
import com.jy.platform.core.message.ResponseMsg;
import com.jy.platform.restclient.http.RestService;

/**
 * @description 基础数据系统接口调用实现
 * @version v1.0
 * @author shengzhoutao
 * @Date 2015-7-29
 */
@Service("com.jy.modules.cims.interact.CIRBaseDataSysImpl")
public class CIRBaseDataSysImpl {
	private static final Logger logger = LoggerFactory.getLogger(CIRBaseDataSysImpl.class);

	private static final String SYSID_BASEDATA = "interact.sysid.base_data_sys"; // 基础数据系统ID属性key
	private static final String IRT_URL_VALIDATE_CUSTOMER = "/api/customer/customer/validate/v1"; // 客户验证查询接口地址
	private static final String IRT_URL_CREATEORUPDATE_CUSTOMER = "/api/customer/customer/createOrupdate/v1"; // 客户新增或修改接口地址
	private static final String IRT_URL_REPAYMENT_PLAN = "/api/contract/repaymentPlan/search/v1"; // 还款计划查询接口地址

	private String appId = PropertyUtil.get(SYSID_BASEDATA); // 基础数据系统rest服务appId
	private String serviceUrl = RestService.getServiceUrl(appId);// 基础数据系统rest服务地址

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	public IInteractAssist iInteractAssist;

	/**
	 * @description 调用客户验证查询接口
	 * @param customerDto
	 *            客户信息对象
	 * @return JResult 返回结果值
	 */
	public JResult validateCustomer(final CustomerDto customerDto) {
		JResult result = new JResult();
		result.setSuccess(false);
		try {
			RequestCustomerValidateDTO request = new RequestCustomerValidateDTO();
			SimpleBeanUtils.copyBean2Bean(request, customerDto);

			StringBuffer url = new StringBuffer(serviceUrl).append(IRT_URL_VALIDATE_CUSTOMER).append("?");
			url.append(getParameterValue(request, null));

			String message = HttpUtils.getRequest(url.toString());
			if (null == message) {
				return result;
			}

			ResponseCustomerValidateDTO response = JSON.parseObject(message, ResponseCustomerValidateDTO.class);
			if (null == response) {
				return result;
			}
			if (null == response.getResponseBody()) {
				return result;
			}

			result.setSuccess(true);
			result.setErrCode(response.getResponseBody().getStatus());// 返回状态码
			result.setErrMsg(response.getResponseBody().getMsg());// 返回状态信息

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("custCode", response.getResponseBody().getCrCode());// 客户编码

			result.setMap(map);
		} catch (Exception e) {
			logger.error("调用客户验证查询接口异常:", ExceptionUtils.getStackTraceAsString(e));
		}

		return result;
	}

	/**
	 * @description 调用客户新增或修改接口
	 * @param customerDto
	 *            客户信息对象
	 * @return JResult 返回结果值
	 */
	public JResult createOrupdateCustomer(final CustomerDto customerDto) {
		JResult result = new JResult();
		result.setSuccess(false);
		try {
			RequestCustomerCreateOrupdateDTO request = new RequestCustomerCreateOrupdateDTO();
			SimpleBeanUtils.copyBean2Bean(request, customerDto);

			String parameterValue = JSON.toJSONString(request, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue,
					SerializerFeature.WriteNullBooleanAsFalse);

			StringBuffer url = new StringBuffer(serviceUrl).append(IRT_URL_CREATEORUPDATE_CUSTOMER).append("");

			String message = HttpUtils.postRequest(url.toString(), parameterValue);
			if (null == message) {
				return result;
			}

			ResponseCustomerValidateDTO response = JSON.parseObject(message, ResponseCustomerValidateDTO.class);
			if (null == response) {
				return result;
			}
			if (null == response.getResponseBody()) {
				return result;
			}

			result.setSuccess(true);
			result.setErrCode(response.getResponseBody().getStatus());// 返回状态码
			result.setErrMsg(response.getResponseBody().getMsg());// 返回状态信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("custCode", response.getResponseBody().getCrCode());// 客户编码

			result.setMap(map);
		} catch (Exception e) {
			logger.error("调用客户新增或修改接口异常:", ExceptionUtils.getStackTraceAsString(e));
		}

		return result;
	}

	/**
	 * @description 调用还款计划查询接口
	 * @param request
	 *            还款计划对象
	 * @return response 返回结果值
	 */
	public ResponseRepaymentPlanDTO getRepaymentPlan(RequestRepaymentPlanDTO request) {
		ResponseRepaymentPlanDTO response = new ResponseRepaymentPlanDTO();
		ResponseMsg<?> responseMsg = null;
		try {
			if (StringUtils.isEmpty(request.getFrontTransNo())) {
				String busiNoForInteract = iInteractAssist.getInteractNo();
				request.setFrontTransNo(busiNoForInteract); // 接口流水号
			}
			request.setSysSource(CimsIrtUrlConstant.IRT_SYSSOURCE_MASTERDATA); // 系统来源
			request.setFrontTransTime(new Timestamp(System.currentTimeMillis())); // 交互事件

			String parameterValue = JSON.toJSONString(request, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue,
					SerializerFeature.WriteNullBooleanAsFalse);

			StringBuffer url = new StringBuffer(serviceUrl).append(IRT_URL_REPAYMENT_PLAN);
			String message = HttpUtils.postRequest(url.toString(), parameterValue);

			responseMsg = JSON.parseObject(message, ResponseMsg.class);
			if (null == responseMsg) {
				return response;
			}
			
			if (null != responseMsg.getResponseBody()) {
				response = JSON.parseObject(JSONObject.toJSONString(responseMsg.getResponseBody()), ResponseRepaymentPlanDTO.class);
			}
		} catch (Exception e) {
			logger.error("调用还款计划查询接口异常:", ExceptionUtils.getStackTraceAsString(e));
		}

		return response;
	}

	/**
	 * @description 根据参数对象的属性返回request传参的字符串
	 * @param obj
	 *            参数对象
	 * @param prefix
	 *            对象嵌套对象的字段属性名
	 * @return 传参的字符串
	 * @throws Exception
	 */
	private static String getParameterValue(Object obj, String prefix) throws Exception {
		StringBuffer url = new StringBuffer();
		Field[] fields = obj.getClass().getDeclaredFields();
		for (int index = 0; index < fields.length; index++) {
			String fieldName = fields[index].getName();
			Class<?> fieldClass = fields[index].getType();
			Object fieldValue = SimpleBeanUtils.getFieldValue(obj, fieldName);

			if (fieldClass.isPrimitive() || String.class.getName().equals(fieldClass.getName())) {
				String fieldValueStr = fieldValue == null ? null : fieldValue.toString();
				if (index != 0) {
					url.append("&");
				}
				if (StringUtils.hasText(prefix)) {
					url.append(prefix).append(".");
				}
				url.append(fieldName).append("=").append(fieldValueStr);
			} else {
				fieldValue = fieldValue == null ? fieldClass.newInstance() : fieldValue;
				url.append("&").append(getParameterValue(fieldValue, fieldName));
			}
		}

		return url.toString();

	}
}
